import 'package:flutter/material.dart';
import '../models/acceptance_form.dart';
import '../services/acceptance_service.dart';
import '../services/pdf_service.dart';
import 'pdf_preview_screen.dart';

class AcceptanceDetailScreen extends StatefulWidget {
  final String formNumber;

  const AcceptanceDetailScreen({
    super.key,
    required this.formNumber,
  });

  @override
  State<AcceptanceDetailScreen> createState() => _AcceptanceDetailScreenState();
}

class _AcceptanceDetailScreenState extends State<AcceptanceDetailScreen> {
  final AcceptanceService _acceptanceService = AcceptanceService();
  final PdfService _pdfService = PdfService();
  final _formKey = GlobalKey<FormState>();
  AcceptanceForm? _form;
  bool _isLoading = true;
  bool _isEditing = false;

  @override
  void initState() {
    super.initState();
    _loadForm();
  }

  Future<void> _loadForm() async {
    setState(() => _isLoading = true);
    try {
      final form = await _acceptanceService.getAcceptanceFormByNumber(widget.formNumber);
      if (mounted) {
        setState(() {
          _form = form;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('加载受理单失败: $e'),
            action: SnackBarAction(
              label: '重试',
              onPressed: _loadForm,
            ),
          ),
        );
      }
    }
  }

  Future<void> _updateForm() async {
    if (_form == null || !_formKey.currentState!.validate()) return;

    setState(() => _isLoading = true);
    try {
      await _acceptanceService.updateAcceptanceForm(_form!);
      if (mounted) {
        setState(() {
          _isLoading = false;
          _isEditing = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('更新成功')),
        );
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('更新失败: $e')),
        );
      }
    }
  }

  Future<void> _deleteForm() async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个受理单吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    setState(() => _isLoading = true);
    try {
      await _acceptanceService.deleteAcceptanceForm(widget.formNumber);
      if (mounted) {
        Navigator.pop(context, true); // 返回列表页面并刷新
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除失败: $e')),
        );
      }
    }
  }

  Future<void> _printForm() async {
    if (_form == null) return;

    setState(() => _isLoading = true);
    try {
      final pdfPath = await _pdfService.generateAcceptanceFormPdf(
        formNumber: _form!.formNumber,
        date: _form!.acceptanceDate.toString().split(' ')[0],
        applicantInfo: {
          'name': _form!.applicantName,
          'contact': _form!.applicantPhone,
          'idNumber': _form!.applicantIdCard,
        },
        respondentInfo: {
          'name': _form!.respondentName,
          'contact': _form!.respondentPhone,
          'idNumber': _form!.respondentIdCard,
        },
        disputeDescription: _form!.disputeDescription,
        acceptorName: _form!.acceptorName,
        acceptorUnit: _form!.acceptorUnit,
        acceptorPhone: _form!.acceptorPhone,
      );

      if (mounted) {
        setState(() => _isLoading = false);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => PdfPreviewScreen(
              pdfPath: pdfPath,
              title: '受理单预览',
            ),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('生成PDF失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      appBar: AppBar(
        title: const Text('受理单详情'),
        actions: [
          if (_form != null && !_isLoading) ...[
            TextButton.icon(
              onPressed: _printForm,
              icon: const Icon(
                Icons.print_rounded,
                color: Color(0xFF6366F1),
              ),
              label: const Text(
                '打印',
                style: TextStyle(
                  color: Color(0xFF6366F1),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            const SizedBox(width: 8),
            TextButton.icon(
              onPressed: _isEditing ? _updateForm : () => setState(() => _isEditing = true),
              icon: Icon(
                _isEditing ? Icons.save_alt_rounded : Icons.edit_note_rounded,
                color: _isEditing ? const Color(0xFF10B981) : const Color(0xFF2563EB),
              ),
              label: Text(
                _isEditing ? '保存' : '编辑',
                style: TextStyle(
                  color: _isEditing ? const Color(0xFF10B981) : const Color(0xFF2563EB),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            const SizedBox(width: 8),
            TextButton.icon(
              onPressed: _deleteForm,
              icon: const Icon(
                Icons.delete_forever_rounded,
                color: Color(0xFFDC2626),
              ),
              label: const Text(
                '删除',
                style: TextStyle(
                  color: Color(0xFFDC2626),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            const SizedBox(width: 16),
          ],
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _form == null
              ? const Center(child: Text('未找到受理单'))
              : SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 基本信息
                        const Text(
                          '基本信息',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF1E293B),
                          ),
                        ),
                        const SizedBox(height: 16),
                        TextFormField(
                          decoration: const InputDecoration(
                            labelText: '受理单号',
                            border: OutlineInputBorder(),
                          ),
                          initialValue: _form!.formNumber,
                          readOnly: true,
                          style: const TextStyle(color: Colors.red),
                        ),
                        const SizedBox(height: 16),
                        TextFormField(
                          decoration: const InputDecoration(
                            labelText: '受理日期',
                            border: OutlineInputBorder(),
                          ),
                          initialValue: _form!.acceptanceDate.toString().split(' ')[0],
                          readOnly: true,
                        ),
                        const SizedBox(height: 16),
                        DropdownButtonFormField<int>(
                          decoration: const InputDecoration(
                            labelText: '状态',
                            border: OutlineInputBorder(),
                          ),
                          value: _form!.status,
                          items: const [
                            DropdownMenuItem(value: 1, child: Text('待处理')),
                            DropdownMenuItem(value: 2, child: Text('处理中')),
                            DropdownMenuItem(value: 3, child: Text('已完成')),
                          ],
                          onChanged: _isEditing
                              ? (value) {
                                  if (value != null) {
                                    setState(() => _form!.status = value);
                                  }
                                }
                              : null,
                        ),
                        const SizedBox(height: 24),

                        // 申请人信息
                        const Text(
                          '申请人信息',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF1E293B),
                          ),
                        ),
                        const SizedBox(height: 16),
                        Row(
                          children: [
                            Expanded(
                              child: TextFormField(
                                decoration: const InputDecoration(
                                  labelText: '申请人姓名',
                                  border: OutlineInputBorder(),
                                ),
                                initialValue: _form!.applicantName,
                                readOnly: !_isEditing,
                                onChanged: _isEditing ? (value) => _form!.applicantName = value : null,
                              ),
                            ),
                            const SizedBox(width: 16),
                            Expanded(
                              child: TextFormField(
                                decoration: const InputDecoration(
                                  labelText: '申请人电话',
                                  border: OutlineInputBorder(),
                                ),
                                initialValue: _form!.applicantPhone,
                                readOnly: !_isEditing,
                                onChanged: _isEditing ? (value) => _form!.applicantPhone = value : null,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 16),
                        TextFormField(
                          decoration: const InputDecoration(
                            labelText: '申请人身份证号',
                            border: OutlineInputBorder(),
                          ),
                          initialValue: _form!.applicantIdCard,
                          readOnly: !_isEditing,
                          onChanged: _isEditing ? (value) => _form!.applicantIdCard = value : null,
                        ),
                        const SizedBox(height: 24),

                        // 被申请人信息
                        const Text(
                          '被申请人信息',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF1E293B),
                          ),
                        ),
                        const SizedBox(height: 16),
                        Row(
                          children: [
                            Expanded(
                              child: TextFormField(
                                decoration: const InputDecoration(
                                  labelText: '被申请人姓名',
                                  border: OutlineInputBorder(),
                                ),
                                initialValue: _form!.respondentName,
                                readOnly: !_isEditing,
                                onChanged: _isEditing ? (value) => _form!.respondentName = value : null,
                              ),
                            ),
                            const SizedBox(width: 16),
                            Expanded(
                              child: TextFormField(
                                decoration: const InputDecoration(
                                  labelText: '被申请人电话',
                                  border: OutlineInputBorder(),
                                ),
                                initialValue: _form!.respondentPhone,
                                readOnly: !_isEditing,
                                onChanged: _isEditing ? (value) => _form!.respondentPhone = value : null,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 16),
                        TextFormField(
                          decoration: const InputDecoration(
                            labelText: '被申请人身份证号',
                            border: OutlineInputBorder(),
                          ),
                          initialValue: _form!.respondentIdCard,
                          readOnly: !_isEditing,
                          onChanged: _isEditing ? (value) => _form!.respondentIdCard = value : null,
                        ),
                        const SizedBox(height: 24),

                        // 纠纷信息
                        const Text(
                          '纠纷信息',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF1E293B),
                          ),
                        ),
                        const SizedBox(height: 16),
                        TextFormField(
                          decoration: const InputDecoration(
                            labelText: '纠纷描述',
                            border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                          ),
                          initialValue: _form!.disputeDescription,
                          maxLines: 5,
                          minLines: 3,
                          readOnly: !_isEditing,
                          onChanged: _isEditing ? (value) => _form!.disputeDescription = value : null,
                          textInputAction: TextInputAction.newline,
                          keyboardType: TextInputType.multiline,
                          style: const TextStyle(
                            fontSize: 16,
                            height: 1.5,
                          ),
                        ),
                        const SizedBox(height: 24),

                        // 受理人信息
                        const Text(
                          '受理人信息',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFF1E293B),
                          ),
                        ),
                        const SizedBox(height: 16),
                        Row(
                          children: [
                            Expanded(
                              child: TextFormField(
                                decoration: const InputDecoration(
                                  labelText: '受理人姓名',
                                  border: OutlineInputBorder(),
                                ),
                                initialValue: _form!.acceptorName,
                                readOnly: !_isEditing,
                                onChanged: _isEditing ? (value) => _form!.acceptorName = value : null,
                              ),
                            ),
                            const SizedBox(width: 16),
                            Expanded(
                              child: TextFormField(
                                decoration: const InputDecoration(
                                  labelText: '受理人电话',
                                  border: OutlineInputBorder(),
                                ),
                                initialValue: _form!.acceptorPhone,
                                readOnly: !_isEditing,
                                onChanged: _isEditing ? (value) => _form!.acceptorPhone = value : null,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 16),
                        TextFormField(
                          decoration: const InputDecoration(
                            labelText: '受理单位',
                            border: OutlineInputBorder(),
                          ),
                          initialValue: _form!.acceptorUnit,
                          readOnly: !_isEditing,
                          onChanged: _isEditing ? (value) => _form!.acceptorUnit = value : null,
                        ),
                      ],
                    ),
                  ),
                ),
    );
  }
} 